package com.note.feng.juc.mutithread;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueExample {

    private static class DelayedElement implements Delayed{

        private long expireTime;
        private String value;

        public DelayedElement(long expireTime, String value){
            this.expireTime = System.currentTimeMillis() + expireTime;
            this.value = value;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            long diff = expireTime - System.currentTimeMillis();
            return unit.convert(diff, TimeUnit.MICROSECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return (int)(this.expireTime - ((DelayedElement)o).expireTime);
        }

        public String getValue(){
            return this.value;
        }

    }
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayedElement> delayQueue = new DelayQueue<>();
        delayQueue.offer(new DelayedElement(2000, "hello"));
        delayQueue.offer(new DelayedElement(10000, "world"));
        System.out.println(delayQueue.size());
        long start = System.currentTimeMillis();
        while (!delayQueue.isEmpty()){
            DelayedElement element = delayQueue.take();
            if(element != null){
                System.out.println(element.getValue());
            }
            System.out.println(System.currentTimeMillis() - start);
        }
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}
